<template>
  <v-layout type="main">
    <!-- <p class="page-title">模型训练</p> -->

    <div class="task-box">
      <drawer-box class="infinite-list" @unfold="unfoldChange" :key="forceRerenderKey">
        <template slot="add">
          <div class="infinite-search">
            <el-input prefix-icon="el-icon-search" v-model="Pagedata.name" class="search" placeholder="请输入内容"
              @input="getDetail" />
            <a href="javascript:;" class="add el-icon-plus" @click="$router.push({ path: '/task/detail' })">新增</a>
          </div>
        </template>
        <div class="utils">
          <div class="all-check">
            <el-checkbox v-model="allChecked" />
            <span>模型训练列表</span>
          </div>
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              排序<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>名称排序</el-dropdown-item>
              <el-dropdown-item>时间排序</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <template v-if="!isCollapse">
          <div :class="['infinite-item', { 'is-active': item.id === detailData.id }]" v-for="item in taskList"
            :key="item.id" @click="handleChange(item)">
            <!-- <div class="title" @click="$router.push({ path: '/task/code', query: { id: item.id } })> -->
            <div class="infinite-item-left">
              <el-checkbox v-model="item.checked" />
            </div>
            <div class="infinite-item-center">
              <div class="title">
                <span>{{ item.name }}</span>
              </div>
              <div class="item tag">
                <el-tag effect="dark" size="mini">{{ item.create_user && item.create_user.nick_name }}</el-tag>
                <el-tag type="info" effect="dark" size="mini">{{ item.create_time }}</el-tag>
              </div>
              <div class="item desc">
                {{ item.desc }}
              </div>
            </div>
            <!-- <div class="tag">
              <el-tag effect="dark" size="mini">{{ item.create_user && item.create_user.nick_name }}</el-tag>
              <el-tag type="info" effect="dark" size="mini">{{ item.create_time }}</el-tag>
            </div> -->
          </div>
        </template>
        <template v-else>
          <el-table :data="taskList" stripe style="width: 100%" class="drawer-box-table">
            <el-table-column prop="name" label="名称">
              <template slot-scope="scope">
                <span @click="tableItemHandler(scope.row)" style="cursor: pointer;">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="create_user.nick_name" label="创建人"></el-table-column>
            <el-table-column label="描述">
              <template slot-scope="scope">
                {{ scope.row.desc }}
              </template>
            </el-table-column>
            <el-table-column prop="create_time" label="创建时间"></el-table-column>
            <el-table-column prop="update_time" label="更新时间"></el-table-column>
          </el-table>
        </template>
      </drawer-box>

      <div class="task-container">
        <div v-if="version != null">
          <!-- <div class="detail-box" v-if="!$route.meta.hideDetails">
            <div class="pic">
              <v-image class="avatar" alt="" />
            </div>
            <div class="word">
              <h3 class="title">
                <h3 class="info-title"> {{ detailData.name }}<i class="el-icon-edit-outline alick-btn-edit"
                    @click="updateTask" />
                </h3>
                <el-button class="back" type="text" icon="el-icon-right" @click="$router.push({ path: '/task' })" />
              </h3>
              <span>状态：<strong :class="['alick-layout-status', version.status]">{{
                statusMap[version.status]
              }}</strong></span> {{ detailData.desc }}
              <div class="alick-handle-btns">

                <a class="handle-btn" href="javascript:;" @click="start" v-show="version.status == 'terminated'">启动</a>
                <a class="handle-btn" href="javascript:;" @click="stop" v-show="version.status != 'terminated'">停止</a>

                <el-popover placement="bottom-end" width="80" trigger="hover">
                  <div class="alick-popover-handle-btns">
                    <a class="handle-btn" href="javascript:;" @click="exportModel"
                      v-show="version.status == 'terminated'">导出模型</a>
                    <a class="handle-btn" href="javascript:;" @click="addVersion">新增版本</a>
                  </div>
                  <a class="handle-btn" href="javascript:;" slot="reference">更多</a>
                </el-popover>
              </div>
            </div>
          </div>
          <div>
            <div class="select-ver clearfix">
              <span class="label">版本</span>
              <el-select class="select" v-model="version" value-key="id" @change="versionChange">
                <el-option v-for="item in versionOptions" :value="item" :label="item.version" :key="item.id">
                </el-option>
              </el-select>
            </div>
            <p class="commit-info">
              <strong>提交信息：</strong>{{ version.commit_msg }}
            </p>
          </div> -->
          <!-- <el-radio-group v-model="nowRouter" size="medium" @change="skip" class="nav-alike"
            v-show="!$route.meta.hideDetails">
            <el-radio-button :label="e.name" v-for="(e, i) in thisRouter" :key="i">
              <span class="nav-alike-item">{{ e.meta.title }}</span>
            </el-radio-button>
          </el-radio-group> -->

          <div class="code-description">
            <div class="code-desc-header">
              <div class="title">
                <div class="title-header">
                  <span>{{ detailData.name }}</span>
                  <i class="el-icon-edit-outline alick-btn-edit" @click="updateTask" />
                </div>

                <div class="code-tags">
                  <el-tag effect="dark" size="mini">
                    {{
                      detailData.create_user && (detailData.create_user.nick_name ||
                        detailData.create_user.username)
                    }}
                  </el-tag>

                  <el-tag type="danger" effect="dark" size="mini" v-if="version.status === 'terminated'">
                    {{ statusMap[version.status] }}
                  </el-tag>
                  <el-tag type="warning" effect="dark" size="mini"
                    v-else-if="version.status != 'terminated' && version.status != 'running'">
                    {{ statusMap[version.status] }}
                  </el-tag>
                  <el-tag type="success" effect="dark" size="mini" v-else>
                    {{ statusMap[version.status] }}
                  </el-tag>

                  <el-tag type="info" effect="dark" size="mini">{{ detailData.create_time }}</el-tag>
                </div>
              </div>

              <div class="code-status">
                <plug-state :statusStr="version.status" />
              </div>
            </div>

            <!-- <div class="desc-container">
          <el-input type="textarea" placeholder="暂无描述信息" :autosize="{ minRows: 4, maxRows: 4 }" disabled
            v-model="detailData.desc" style="cursor: pointer" />
        </div> -->
          </div>
          <div>
            <div class="select-ver clearfix">
              <span class="label">版本</span>
              <el-select class="select" v-model="version" value-key="id" @change="versionChange">
                <el-option v-for="item in versionOptions" :value="item" :label="item.version" :key="item.id">
                </el-option>
              </el-select>
            </div>
            <p class="commit-info">
              <strong>提交信息：</strong>{{ version.commit_msg }}
            </p>
          </div>

          <el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
            <el-tab-pane :label="e.meta.title" :name="`${e.name}`" v-for="(e, i) in thisRouter" :key="i" />
          </el-tabs>

          <div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">
            <router-view class="content-detail" :detailData=detailData :version.sync=version v-if="version != null" />
          </div>

          <el-form class="form myself-form" ref="taskForm" :model="taskForm" :rules="taskSubmitRules" label-width="120px">
            <el-dialog :visible.sync="showTaskDialog" title="模型训练" width="840px">
              <el-form-item label="名称" prop="name">
                <el-input type="text" v-model="taskForm.name" />
              </el-form-item>
              <el-form-item label="描述" prop="desc">
                <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
              </el-form-item>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="commitTask">确定</el-button>
                <el-button class="none-type" @click="cancelTask">取消</el-button>
              </span>
            </el-dialog>
          </el-form>
          <div v-if="showExportModelDialog">
            <plug-export-model :show_file=showExportModelDialog @infoShow="infoShowExport" :model_id=model_id
              :biz_id=version.id :business_type="2" />
          </div>
        </div>
      </div>
    </div>
  </v-layout>
</template>

<script>
import plugState from '@/components/module/plug-state'
import drawerBox from "@/components/module/drawer-box.vue"
import { getModelBySource } from "@/api/model"
import plugExportModel from '@/components/module/plug-export-model'
import { mapActions, mapState } from "vuex"
import { putTask, getTaskDetail, getTaskVersionDetail, getAllTaskVersions, startTaskVersion, stopTaskVersion, createPvc, deletePvc } from '@/api/task'
export default {
  data() {
    return {
      nowRouter: this.$route.name,
      thisRouter: [],
      // detailData: {},
      version: null,
      versionOptions: [],
      modelForm: {},
      taskForm: { visibility: 0 },
      taskSubmitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到200个字符" },
        ],
      },
      showTaskDialog: false,
      showExportModelDialog: false,
      modelOptions: [],
      model: null,
      source_version_id: this.$route.query.source_version_id,
      allChecked: false,
      forceRerenderKey: 0,
      // isCollapse: false
    };
  },
  components: {
    plugExportModel,
    drawerBox,
    plugState
  },
  methods: {
    ...mapActions(["getTaskList", "updateDetail"]),
    skip() {
      let path = `/task/${this.thisRouter.filter(e => e.name == this.nowRouter)[0].path}`
      if (path == this.$route.path) return
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id
        }
      })
    },
    async getTaskVersions() {
      let ret = await getAllTaskVersions({ taskId: this.$route.query.id })
      this.versionOptions = ret.data
      let ve = null
      if (this.versionOptions.length > 0) {
        ve = this.versionOptions[0]
      }
      if (this.source_version_id) {
        for (let i = 0; i < this.versionOptions.length; i++) {
          if (this.source_version_id == this.versionOptions[i].id) {
            ve = this.versionOptions[i]
          }
        }
      }
      let res = await getTaskVersionDetail({ id: ve.id })
      let data = res.data
      this.version = data
      this.$forceUpdate();
    },
    async versionChange() {
      console.log("version", this.version)
      let res = await getTaskVersionDetail({ id: this.version.id })
      let data = res.data
      this.version = data
      this.detailData = JSON.parse(JSON.stringify(this.detailData))
    },
    async getDetail() {
      if (this.$route.query.id) {
        let res = await getTaskDetail({ id: this.$route.query.id })
        // this.detailData = res.data
        this.updateDetail(res.data)
        this.taskForm = JSON.parse(JSON.stringify(this.detailData))
        this.getTaskVersions()

      }
    },
    async handleChange(val) {
      // console.log(val);
      // this.detailData = val;
      this.updateDetail(val)
      this.$router.push({
        path: "/task",
        query: {
          id: val.id
        }
      })
    },
    unfoldChange(val) {
      this.$store.commit('TASKUNFOLDCHANGE', val);
    },
    updateTask() {
      this.showTaskDialog = true
    },
    cancelTask() {
      this.showTaskDialog = false
    },
    commitTask() {
      this.$refs.taskForm.validate(async (valid) => {
        if (valid) {
          await putTask(this.task)
          this.showTaskDialog = false
        }
      })
    },
    updateVersion() {
      if (this.version) {
        let query = {
          id: this.version.id
        }
        this.$router.push({
          path: '/task/versionsdetail',
          query
        })
      }
    },
    addVersion() {
      let version = 1
      if (this.detailData.version_index) {
        version = 'v' + (this.detailData.version_index + 1)
      }
      let query = {
        task_id: this.detailData.id,
        version: version,
        source_version_id: this.version.id
      }
      this.$router.push({
        path: '/task/versionsdetail',
        query
      })
    },
    async exportModel() {
      if (!this.$route.query.id) return
      let data = {
        source: this.version.id
      }
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id
      }
      this.showExportModelDialog = true
      console.log("showExportModelDialog", this.showExportModelDialog)
    },
    infoShowExport(data) {
      this.showExportModelDialog = data
    },

    async start() {
      if (this.version) {
        try {
          var res = await createPvc({ id: this.version.id })
          console.log("res:", res)
          var res1 = await startTaskVersion({ id: this.version.id });
          if (res1.code != 200) {
            await deletePvc({ id: this.version.id })
          }
        } catch (e) {
          //console.log("e:",e)
          await deletePvc({ id: this.version.id })
        }
      }

    },
    async stop() {
      if (this.version) {
        await stopTaskVersion({ id: this.version.id });
        this.getDetail()
        this.getTaskVersions()
      }
    },
  },
  computed: mapState({
    taskList: state => state.taskStore.taskList,
    isCollapse: state => state.taskStore.isCollapse,
    detailData: state => state.taskStore.detail,
  }),
  mounted() {
    let temp = this.$router.options.routes.filter(
      e => e.name == 'task' && e.children
    )
    this.thisRouter = temp[0].children.filter(e => !e.meta.hideDetails)
    this.getTaskList()
    this.getDetail()
    this.$EventBus.$on('task', e => {
      console.log(e)
      this.getDetail()
      this.getTaskVersions()
    })
  },
  destroyed() {
    this.$EventBus.$off('task')
  },
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

.task-box {
  display: flex;

  .task-container {
    width: 100%;
    // margin-left: 220px;
    // margin-left: 260px;
    // margin-left: 570px;
    margin-left: 600px;
  }
}
</style>
